//
//  ZBBaseDebugView.m
//  DevDemo
//
//  Created by BO ZHOU on 2021/5/6.
//

#import "ZBBaseDebugView.h"
#import "TaskData.h"
#import "DelayTool.h"

static ZBBaseDebugView* instance = nil;

@interface ZBBaseDebugView()<UIGestureRecognizerDelegate>


/// 展开之前的位置
@property (nonatomic, assign) CGRect beforeExpandFrame;

/// 隐藏回调包装类
@property (nonatomic, strong) TaskData* delayHideBlock;

/// 小圆点图片
@property (nonatomic, strong) UIImageView* iconImageView;


@end

@implementation ZBBaseDebugView


+ (instancetype)shared {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self class] new];
        instance.frame = CGRectMake(0, 88, instance.wh, instance.wh);
        instance.backgroundColor = [[UIColor cyanColor] colorWithAlphaComponent:0.5];
        instance.layer.cornerRadius = instance.wh/2;
        instance.layer.masksToBounds = true;
    });

    return instance;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.wh = 60;
        self.expandWH = 300;
        self.edgeMargin = 6;
        self.beforeExpandFrame = CGRectZero;
        
        
        [self addSubview:self.iconImageView];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.iconImageView.frame = self.bounds;
        });
        
        [self addGesture];
        self.delayHideBlock = [self delayToHalfAlpha];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        exit(0);
    }
    return self;
}

-(void)addGesture {
    
    // 添加滑动收拾
    UIPanGestureRecognizer* ges = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
    
    [self addGestureRecognizer:ges];
    
    
    // 添加单机收拾
    UITapGestureRecognizer* tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    tapGes.delegate = self;
    [self addGestureRecognizer:tapGes];
}


/**
 * 滑动手势执行
 */
-(void)panGestureAction:(UIPanGestureRecognizer*)gesture {
    
    CGPoint translationPoint = [gesture translationInView:self];
    
    self.frame = CGRectMake(self.frame.origin.x + translationPoint.x, self.frame.origin.y + translationPoint.y, self.frame.size.width, self.frame.size.height);
    
    [gesture setTranslation:CGPointZero inView:self];
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self.delayHideBlock cancel];
        [self.layer removeAllAnimations];
    } else if (gesture.state == UIGestureRecognizerStateEnded) {
        
        CGFloat delataLeading = self.frame.origin.x;
        CGFloat deltaTrainling = fabs(CGRectGetMaxX(self.frame) - UIScreen.mainScreen.bounds.size.width);
        
        CGFloat finalPointX = self.frame.origin.x;
        CGFloat finalPointY = self.frame.origin.y;
        
        if (delataLeading < deltaTrainling) {
            finalPointX = self.edgeMargin;
        } else {
            finalPointX = UIScreen.mainScreen.bounds.size.width - self.frame.size.width - self.edgeMargin;
        }
        
        if (self.frame.origin.y < 44) {
            finalPointY = 44;
        } else if (self.frame.origin.y > UIScreen.mainScreen.bounds.size.height - self.frame.size.height - 34) {
            finalPointY = UIScreen.mainScreen.bounds.size.height - self.frame.size.height - 34;
        }
        
        if (self.isExpande == false) {
            [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                CGRect frame = self.frame;
                frame.origin = CGPointMake(finalPointX, finalPointY);
                self.frame = frame;
            } completion:^(BOOL finished) {
                self.delayHideBlock = [self delayToHalfAlpha];
            }];
        } else {
            [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.iconImageView.alpha = 0;
                self.frame = CGRectMake(UIScreen.mainScreen.bounds.size.width/2 - self.expandWH/2, finalPointY, self.expandWH, self.expandWH);
            } completion:nil];
        }
    }
}

/**
 * 单机收拾执行
 */
-(void)tapGesture:(UITapGestureRecognizer*)gesture {
    [self.delayHideBlock cancel];
    
    [self.layer removeAllAnimations];
    
    self.isExpande = true;
}


/**
 * 延迟透明化
 */
-(TaskData*)delayToHalfAlpha {
    
    return [DelayTool delayWithTime:2 task:^{
        
        if (self.isExpande == false) {
            CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
            animation.fromValue = @1;
            animation.toValue = @0.55;
            animation.duration = 1;
            animation.repeatCount = 1;
            animation.removedOnCompletion = false;
            animation.fillMode = kCAFillModeForwards;
            
            [self.layer addAnimation:animation forKey:@"opacity"];
        }
    }];
}


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView* view = [super hitTest:point withEvent:event];
    
    if (view == nil) {
        self.isExpande = false;
        return nil;
    }
    
    if (view == self) {
        NSLog(@"自身电机");
    } else if ([self.subviews containsObject:view]) {
        NSLog(@"自身的子控件点击");
    }
    return view;
}



- (UIImageView *)iconImageView {
    if (_iconImageView == nil) {
        _iconImageView = [UIImageView new];
        _iconImageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", SelfBundle(), @"yuandian.png"]];
    }
    return _iconImageView;
}



- (void)setIsExpande:(bool)isExpande {
    
    if (_isExpande == isExpande) {
        return;
    }
    
    _isExpande = isExpande;
    
    if (isExpande) {
        // 展开
        self.alpha = 1;
        self.beforeExpandFrame = self.frame;
        
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.iconImageView.alpha = 0;
            CGFloat toY = self.frame.origin.y;
            
            if (self.frame.origin.y + self.expandWH > UIScreen.mainScreen.bounds.size.height) {
                toY = UIScreen.mainScreen.bounds.size.height - self.expandWH - 34;
            }
            
            self.frame = CGRectMake(UIScreen.mainScreen.bounds.size.width/2 - self.expandWH/2, toY, self.expandWH, self.expandWH);
        } completion:^(BOOL finished) {
            if (self.isExpande) {
                [self expandDidComplete];
            }
        }];
    } else {
        
        // 收起
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.iconImageView.alpha = 1;
            self.frame = self.beforeExpandFrame;
        } completion:^(BOOL finished) {
            if (self.isExpande == false) {
                self.delayHideBlock = [self delayToHalfAlpha];
            }
        }];
    }
}


+ (void)show {
    [[self shared] show];
}

+ (void)hide {
    [[self shared] hide];
}

+(BOOL)isOpen {
    return [[self shared] isOpen];
}

-(void)show {
    
    self.isOpen = true;
    
    UIWindow* window = UIApplication.sharedApplication.keyWindow;
    
    if ([window.subviews containsObject:self]) {
        [UIView animateWithDuration:0.25 animations:^{
            self.alpha = 1;
        }];
    } else {
        [window addSubview:self];
        self.alpha = 0;
        [UIView animateWithDuration:0.25 animations:^{
            self.alpha = 1;
        }];
    }
    
    [window bringSubviewToFront:self];
}

-(void)hide {
    
    self.isOpen = false;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
    }];
}


-(void)expandDidComplete {
    NSLog(@"子类实现");
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    UIView* view = touch.view;
    
    if (view == false) {
        return false;
    }
    
    UIView* superview = view.superview;
    if (superview) {
        if ([NSStringFromClass([superview class]) isEqual: @"ZBDebugCollectionViewCell"]) {
            return false;
        }
    }
    
    return true;
}

@end
